import MobileSelect, { CascadeData } from 'mobile-select';
import { useEffect, useRef, useState } from 'react';
import { excludedOptions } from '../../types';
import regions from './area.json';
interface Props {
  provinceName?: string;
  cityName?: string;
  countyName?: string;
  excludedList: excludedOptions;
  onChange: (v: string[]) => void;
}
interface Options {
  value?: string;
  label: string;
  disabled?: boolean;
  children?: Options[];
}

export default function MReceiptPicker({ provinceName, cityName, countyName, excludedList, onChange }: Props) {
  const pickerRef = useRef<MobileSelect | null>(null);
  const [select, setSelect] = useState(false);
  const [regionsList, setregionsList] = useState<Options[]>(regions);

  // 将滚轮回滚到选择的数据
  useEffect(() => {
    RefsChange()
  }, [provinceName, cityName, countyName]);
  function RefsChange(v?: any) {
    if (pickerRef.current && provinceName && cityName && countyName) {
      let pidx = -1;
      let cidx = -1;
      let countyidx = -1;
      pidx = regionsList.findIndex((item) => item.label.substring(0, 2) === provinceName.substring(0, 2));
      if (pidx >= 0) {
        cidx = regionsList[pidx].children!.findIndex((item) => item.label.substring(0, 2) === cityName.substring(0, 2));
        if (cidx >= 0) {
          countyidx = regionsList[pidx].children![cidx].children!.findIndex(
            (item) => item.label.substring(0, 2) === countyName.substring(0, 2)
          );
        }
      }

      if (pidx >= 0) {
        pickerRef.current.locatePosition(0, pidx);
      }
      if (cidx >= 0) {
        pickerRef.current.locatePosition(1, cidx);
      }
      if (countyidx >= 0) {
        pickerRef.current.locatePosition(2, countyidx);
      }
    }
  }
  useEffect(() => {
    const filefilterRegions = filterRegions(regions, excludedList);
    let data: Options[] =
      filefilterRegions && filefilterRegions.length > 0 ? filefilterRegions : [{ label: '暂无可选城市' }];
    setregionsList(data);
  }, [excludedList]);

  // 遍历去除禁选地区
  function filterRegions(regionsList: Options[], excludedRegions: excludedOptions) {
    return regionsList
      .filter((provinceObj) => !excludedRegions.provinces.includes(provinceObj.label))
      .map((provinceObj) => ({
        label: provinceObj.label,
        children: provinceObj
          .children!.filter((cityObj: Options) => !excludedRegions.cities.includes(cityObj.label))
          .map((cityObj: Options) => ({
            label: cityObj.label,
            children: cityObj.children!.filter((dist: Options) => !excludedRegions.district.includes(dist.label)),
          })),
      }));
  }

  function handleRef(v?: any) {
    if (pickerRef.current) {
      pickerRef.current.updateWheels(regionsList);
      RefsChange()
      return;
    }
    let data = regionsList;
    pickerRef.current = new MobileSelect({
      trigger: '#m-receipt-picker',
      title: '地址选择',
      wheels: [{ data }],
      keyMap: { id: 'label', value: 'label', childs: 'children' },
      onChange: (cur: any) => {
        if (!select) {
          setSelect(true);
        }
        onChange((cur as CascadeData[]).map((i) => (i as CascadeData).label));
      },
    });
  }
  let _value = provinceName + ' ' + cityName + ' ' + countyName;
  return (
    <div
      id="m-receipt-picker"
      className={`value ${select || !!_value.trim() ? '' : 'place-holder'}`}
      ref={(v) => handleRef(v)}
    >
      {!!_value.trim() ? _value : '请选择地区'}
    </div>
  );
}
